import React, { useState, useEffect } from 'react'
import { NavBar, List, InputItem, Grid, Icon } from 'antd-mobile'
import { sendMsg } from '../main/socketClient'
import {readMsg} from '../../api/index'
import { connect } from 'react-redux'
import { getUserByCookie, getMsgList } from '../../api/index'

const Item = List.Item
// import QueueAnim from 'rc-queue-anim'


function Chat(props) {
    const [content, setcontent] = useState(null)
    const [isShow, setisShow] = useState(false)
    const to = props.match.params.userId;
    const { userInfo = {} } = props.user
    const from = userInfo._id

    const { chatMsg, users } = props.chat
    const chatId = [to, from].sort().join("_")
    const msgDatasource = chatMsg.filter(i => i.chat_id == chatId)

    useEffect(() => {
        window.scrollTo(0, document.body.scrollHeight)

        //read 消息
        return () => {
            readMsg({from: to}).then((result) => {
                console.log(result);
                getMsgList().then((res) => {
                    const { chatMsg } = res
                    let unReadCount = chatMsg.filter(i => !i.read && i.to ==userInfo._id ).length
                    props.dispatch({ type: "Receive_Msg_List", data: {...res, unReadCount} })
                  }).catch((err) => {
                    alert(err, "获取消息列表失败")
                  });
            }).catch((err) => {
                console.log(err);
            });
        }
    }, [])

    // 如果数据还没有返回！！  使用这中方式停止渲染
    if (!users[to]) {
        return null
    }

    const toheader = users[to].header
    const targetIcon = toheader ? require(`../../assets/images/${toheader}.png`) : null
    console.log("msgDatasource", msgDatasource);
    const toggleShow = () => {

    }

    const handleSend = () => {
        if (content) {
            let param = { from, to, content }
            sendMsg(param)
            setcontent(null)
            window.scrollTo(0, document.body.scrollHeight)
        }
    }

    return <div id='chat-page'>
        <NavBar
            icon={<Icon type='left' />}
            className='sticky-header'
            onLeftClick={() => props.history.goBack()}
        >
            {users[to].username}
        </NavBar>
        <List style={{ marginTop: 50, marginBottom: 50 }}>
            {/* <QueueAnim type='left' delay={100}> */}
            {
                msgDatasource.map(msg => {
                    if (to === msg.from) {// 对方发给我的
                        return (
                            <Item
                                key={msg._id}
                                thumb={<img src={targetIcon} />}
                            >
                                {msg.content}
                            </Item>
                        )
                    } else { // 我发给对方的
                        return (
                            <Item
                                key={msg._id}
                                className='chat-me'
                                extra='我'
                            >
                                {msg.content}
                            </Item>
                        )
                    }
                })
            }
            {/* </QueueAnim> */}

        </List>

        <div className='am-tab-bar'>
            <InputItem
                placeholder="请输入"
                value={content}
                onChange={val => setcontent(val)}
                onFocus={() => setisShow(true)}
                extra={
                    <span>
                        <span onClick={toggleShow} style={{ marginRight: 5 }}>😊</span>
                        <span onClick={handleSend}>发送</span>
                    </span>
                }
            />
            {/* {isShow ? (
                <Grid
                    data={this.emojis}
                    columnNum={8}
                    carouselMaxRow={4}
                    isCarousel={true}
                    onClick={(item) => {
                        this.setState({ content: this.state.content + item.text })
                    }}
                />
            ) : null} */}

        </div>
    </div>

}

export default connect(
    state => ({ chat: state.chat, user: state.user })
)(Chat)